//
//  RespView.swift
//  icloud
//
//  Created by raymond on 2022/6/5.
//

import SwiftUI

struct RespView: View {
  @State private var results = [Result]()
  var body: some View {
    List(results, id: \.trackId) { item in
      VStack(alignment: .leading) {
        Text(item.trackName)
          .font(.headline)
        Text(item.collectionName)
      }
    }
    .onAppear(perform: loadData)
  }
  
  func loadData(){
    guard let url = URL(string: "https://itunes.apple.com/search?term=taylor+swift&entity=song") else {
      print("Invalid URL")
      return
    }
    let request = URLRequest(url: url)
    URLSession.shared.dataTask(with: request) { data, response, error in
      // step 4
      if let data = data {
        if let decodedResponse = try? JSONDecoder().decode(Resp.self, from: data) {
          // 我们得到了有用的数据 - 返回到主线程
          DispatchQueue.main.async {
            // 更新我们的UI
            self.results = decodedResponse.results
          }
          
          // 所有工作都完成了，所以可以退出了
          return
        }
      }
      
      // 如果代码跑到这里了，说明发生了某些错误
      print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
    }.resume()
  }
}

struct RespView_Previews: PreviewProvider {
  static var previews: some View {
    RespView()
  }
}
